package com.xiaoyy.core.oplog.config.aspect;


import cn.hutool.core.date.DateUtil;
import com.xiaoyy.core.common.enums.BoolEnum;
import com.xiaoyy.core.config.store.SessionHelper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 统一处理操作人信息
 * @author chenzh
 * @date 2019/03/25
 */

@Aspect
@Component
public class OperationInfoAspect {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(OperationInfoAspect.class);

	private static final String CREATENAME = "createName";
	private static final String CREATETIME = "createTime";

	private static final String UPDATENAME = "updateName";
	private static final String UPDATETIME  = "updateTime";

	private static final String DEL = "del";

	/**
	 * insert操作统一记录操作信息
	 * @param joinPoint
	 */
	@Before("execution(* com.xiaoyy..*.dao.mapper..*.insert*(..))")
	private void beforeInsert(JoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
		if (args != null && args.length > 0) {
			Object argument = args[0];

			insertSet(argument);


		}
	}

	private void insertSet(Object argument){
		BeanWrapper beanWrapper = new BeanWrapperImpl(argument);

		Date date = DateUtil.date();
		//创建日期
		if (beanWrapper.isWritableProperty(CREATETIME)) {
			beanWrapper.setPropertyValue(CREATETIME, date);
		}
		//修改日期
		if (beanWrapper.isWritableProperty(UPDATETIME)) {
			beanWrapper.setPropertyValue(UPDATETIME, date);
		}

		//创建人
		if (beanWrapper.isWritableProperty(CREATENAME)) {
			beanWrapper.setPropertyValue(CREATENAME, SessionHelper.getUserName());
		}
		//修改人
		if (beanWrapper.isWritableProperty(UPDATENAME)) {
			beanWrapper.setPropertyValue(UPDATENAME, SessionHelper.getUserName());
		}
		//新增的时候默认是否删除为否
		if (beanWrapper.isWritableProperty(DEL)) {
			beanWrapper.setPropertyValue(DEL, BoolEnum.FALSE.getType());
		}
	}
	/**
	 * update操作统一记录修改人、修改时间
	 * @param joinPoint
	 */
	@Before("execution(* com.xiaoyy..*.dao.mapper..*.update*(..))")
	private void beforeUpdate(JoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
		if (args != null && args.length > 0) {
			Object argument = args[0];

			updateSet(argument);
		}
	}
	private void updateSet(Object argument){
		BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
		Date date = DateUtil.date();
		//修改日期
		if (beanWrapper.isWritableProperty(UPDATETIME)) {
			beanWrapper.setPropertyValue(UPDATETIME, date);
		}
		//修改人
		if (beanWrapper.isWritableProperty(UPDATENAME)) {
			beanWrapper.setPropertyValue(UPDATENAME, SessionHelper.getUserName());
		}
	}
}













